from collections import OrderedDict

from django.conf import settings
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination


class CustomPagePagination(PageNumberPagination):
    """
    自定义返回数据格式
    """
    page_size = settings.PAGE_SIZE  # 默认10
    page_size_query_param = 'limit'  # 传一个size参数 一页显示多少  http://127.0.0.1:8000/v1/api/posts/?page=1&limit=3
    max_page_size = settings.MAX_PAGE_SIZE  # 一页显示最大100个
    page_query_param = 'page'  # 页码

    def get_paginated_response(self, data):
        """
        返回数据
        :param data:
        :return:
        """
        return Response(OrderedDict([
            ('code', 200),
            ('msg', '获取成功~~'),
            ('total', self.page.paginator.count),
            ('page', self.page.number),
            ('limit', self.get_page_size(self.request)),
            ('pages', self.page.paginator.num_pages),
            ('next', self.page.has_next()),
            ('previous', self.page.has_previous()),
            ('data', data)
        ]))

    def get_paginated_response_schema(self, schema):
        """
        定义返回数据规则
        :param schema:
        :return:
        """
        return {
            'type': 'object',
            'properties': {
                'code': {
                    'type': 'integer',
                    'example': 200,
                },
                'msg': {
                    'type': 'string',
                    'nullable': True,
                },
                'total': {
                    'type': 'integer',
                    'example': 101,
                },
                'page': {
                    'type': 'integer',
                    'example': 1,
                },
                'limit': {
                    'type': 'integer',
                    'example': 10,
                },
                'pages': {
                    'type': 'integer',
                    'example': 11,
                },
                'next': {
                    'type': 'string',
                    'nullable': True,
                },
                'previous': {
                    'type': 'string',
                    'nullable': True,
                },
                'data': schema,
            },
        }
